<template>
  <div class="video-player" @click="togglePlay">
    <video
      ref="videoRef"
      class="video-element"
      :src="videoUrl"
      :poster="coverUrl"
      :muted="isMuted"
      :loop="true"
      crossorigin="anonymous"
      playsinline
      webkit-playsinline
      x5-video-player-type="h5"
      x5-video-player-fullscreen="true"
      x5-video-orientation="portraint"
      preload="metadata"
      @loadstart="onLoadStart"
      @loadedmetadata="onLoadedMetadata"
      @loadeddata="onLoadedData"
      @canplay="onCanPlay"
      @canplaythrough="onCanPlayThrough"
      @play="onPlay"
      @pause="onPause"
      @ended="onEnded"
      @error="onError"
      @stalled="onStalled"
      @suspend="onSuspend"
      @waiting="onWaiting"
    />
    
    <!-- 播放状态指示 -->
    <transition name="fade">
      <div v-if="showPlayIcon" class="play-overlay">
        <div class="play-icon-wrapper">
          <el-icon class="play-icon" :size="60">
            <VideoPlay v-if="!isPlaying" />
            <VideoPause v-else />
          </el-icon>
        </div>
      </div>
    </transition>
    
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
    
    <!-- 音量控制 -->
    <div class="volume-control" @click.stop="toggleMute">
      <el-icon :size="18">
        <Mute v-if="isMuted" />
        <Microphone v-else />
      </el-icon>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onBeforeUnmount, onMounted } from 'vue'
import { VideoPlay, VideoPause, Mute, Microphone } from '@element-plus/icons-vue'

const props = defineProps({
  videoUrl: {
    type: String,
    required: true
  },
  coverUrl: {
    type: String,
    default: ''
  },
  autoplay: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['play', 'pause', 'ended', 'error', 'canplay'])

// 播放器状态
const videoRef = ref(null)
const isPlaying = ref(false)
const isLoading = ref(true)
const isMuted = ref(true)
const showPlayIcon = ref(false)

let hideIconTimer = null

// 切换播放状态
const togglePlay = async () => {
  if (!videoRef.value) return
  
  try {
    if (isPlaying.value) {
      videoRef.value.pause()
    } else {
      const playPromise = videoRef.value.play()
      if (playPromise !== undefined) {
        await playPromise
      }
    }
  } catch (error) {
    // 忽略被中断的播放请求错误，这是正常的用户交互
    if (error.name !== 'AbortError') {
      console.error('播放控制失败:', error)
    }
  }
}

// 切换静音状态
const toggleMute = () => {
  isMuted.value = !isMuted.value
}

// 显示播放图标
const showPlayIconTemp = () => {
  showPlayIcon.value = true
  clearTimeout(hideIconTimer)
  hideIconTimer = setTimeout(() => {
    showPlayIcon.value = false
  }, 800)
}

// 播放器事件处理
const onLoadStart = () => {
  console.log('开始加载视频:', props.videoUrl)
  isLoading.value = true
}

const onLoadedMetadata = () => {
  console.log('视频元数据加载完成:', props.videoUrl)
  if (videoRef.value) {
    console.log('视频时长:', videoRef.value.duration)
    console.log('视频尺寸:', videoRef.value.videoWidth, 'x', videoRef.value.videoHeight)
  }
}

const onLoadedData = () => {
  console.log('视频数据加载完成:', props.videoUrl)
}

const onCanPlay = () => {
  console.log('视频可以播放了:', props.videoUrl)
  isLoading.value = false
  emit('canplay')
  
  if (props.autoplay && !isPlaying.value) {
    nextTick(() => {
      const playPromise = videoRef.value?.play()
      if (playPromise !== undefined) {
        playPromise.catch((error) => {
          // 自动播放被阻止是正常的，不需要报错
          if (error.name !== 'AbortError') {
            console.log('自动播放被阻止:', error.message)
          }
        })
      }
    })
  }
}

const onCanPlayThrough = () => {
  console.log('视频可以完整播放:', props.videoUrl)
  isLoading.value = false
}

const onStalled = () => {
  console.log('视频加载暂停:', props.videoUrl)
}

const onSuspend = () => {
  console.log('视频加载被挂起:', props.videoUrl)
}

const onWaiting = () => {
  console.log('视频等待数据:', props.videoUrl)
  isLoading.value = true
}

const onPlay = () => {
  console.log('视频开始播放:', props.videoUrl)
  isPlaying.value = true
  showPlayIconTemp()
  emit('play')
}

const onPause = () => {
  console.log('视频暂停:', props.videoUrl)
  isPlaying.value = false
  showPlayIconTemp()
  emit('pause')
}

const onEnded = () => {
  isPlaying.value = false
  emit('ended')
}

const onError = (event) => {
  console.error('视频播放错误:', props.videoUrl, event)
  console.error('错误详情:', event.target.error)
  isLoading.value = false
  emit('error', event)
}

// 播放控制方法（供外部调用）
const play = async () => {
  if (videoRef.value && !isPlaying.value) {
    try {
      const playPromise = videoRef.value.play()
      if (playPromise !== undefined) {
        await playPromise
      }
    } catch (error) {
      if (error.name !== 'AbortError') {
        console.error('播放失败:', error)
      }
    }
  }
}

const pause = () => {
  if (videoRef.value && isPlaying.value) {
    videoRef.value.pause()
  }
}

// 监听视频地址变化
watch(() => props.videoUrl, (newUrl, oldUrl) => {
  console.log('视频URL变化:', oldUrl, '->', newUrl)
  if (videoRef.value && newUrl) {
    isLoading.value = true
    videoRef.value.load()
    console.log('强制重新加载视频')
  }
}, { immediate: true })

// 组件卸载时清理
onBeforeUnmount(() => {
  clearTimeout(hideIconTimer)
  if (videoRef.value) {
    videoRef.value.pause()
  }
})

// 组件挂载
onMounted(() => {
  console.log('VideoPlayer挂载，视频URL:', props.videoUrl)
  console.log('视频自动播放:', props.autoplay)
  
  // 检查视频元素
  if (videoRef.value) {
    console.log('视频元素已创建')
    console.log('视频元素网络状态:', videoRef.value.networkState)
    console.log('视频元素准备状态:', videoRef.value.readyState)
    
    // 定时检查视频加载状态
    const checkStatus = () => {
      if (videoRef.value) {
        console.log('视频状态检查:', {
          src: videoRef.value.src,
          networkState: videoRef.value.networkState,
          readyState: videoRef.value.readyState,
          duration: videoRef.value.duration,
          error: videoRef.value.error
        })
        
        // 如果有错误，输出错误信息
        if (videoRef.value.error) {
          console.error('视频错误详情:', {
            code: videoRef.value.error.code,
            message: videoRef.value.error.message
          })
        }
      }
    }
    
    // 3秒后检查一次状态
    setTimeout(checkStatus, 3000)
  }
})

// 暴露方法给父组件
defineExpose({
  play,
  pause,
  videoElement: videoRef
})
</script>

<style lang="scss" scoped>
.video-player {
  position: relative;
  width: 100%;
  height: 100vh;
  background: #000;
  cursor: pointer;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .video-element {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
    background: #000;
    
    @media (max-width: 768px) {
      max-width: 100vw;
      max-height: 100vh;
      width: auto;
      height: auto;
      
      &[style*="landscape"], &[data-orientation="landscape"] {
        width: 100%;
        height: auto;
        object-fit: cover;
      }
    }
    
    @media (orientation: portrait) {
      width: 100%;
      height: auto;
      max-height: 100vh;
      object-fit: contain;
    }
    
    @media (orientation: landscape) {
      width: auto;
      height: 100%;
      max-width: 100vw;
      object-fit: contain;
    }
  }
  
  .play-overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
    pointer-events: none;
    
    .play-icon-wrapper {
      background: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      padding: 20px;
      backdrop-filter: blur(10px);
      
      .play-icon {
        color: rgba(255, 255, 255, 0.9);
        filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.3));
      }
    }
  }
  
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 16px;
    z-index: 5;
    
    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(255, 255, 255, 0.2);
      border-top: 3px solid $primary-color;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    .loading-text {
      color: rgba(255, 255, 255, 0.8);
      font-size: 14px;
    }
  }
  
  .volume-control {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 36px;
    height: 36px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: $text-white;
    cursor: pointer;
    transition: $transition-fast;
    z-index: 10;
    backdrop-filter: blur(10px);
    
    &:hover {
      background: rgba(0, 0, 0, 0.8);
      transform: scale(1.1);
    }
    
    @media (max-width: 768px) {
      top: 60px;
      right: 16px;
      width: 32px;
      height: 32px;
      
      .el-icon {
        font-size: 16px;
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style> 